<template>
  <div class="wrap">
    <div class="header">
      <a-button type="link" class="back" @click="goBack">
        <template #icon>
          <LeftOutlined />
        </template>
        返回
      </a-button>
      <span class="title">{{ isEdit ? "编辑" : "新增" }}</span>
    </div>

    <div class="form">
      <!-- 名称 -->
      <div class="row required">
        <div class="label">名称：</div>
        <div class="field">
          <a-input v-model:value="form.name" placeholder="请输入" allow-clear class="control" />
        </div>
      </div>

      <!-- 应用频道 -->
      <div class="row">
        <div class="label">应用频道：</div>
        <div class="field">
          <a-select v-model:value="form.channel" :options="channelOptions" :loading="channelLoading" placeholder="请选择频道"
            allow-clear show-search :filter-option="false" @search="onSearchChannel"
            @dropdownVisibleChange="onChannelDropdown" class="control" />
        </div>
      </div>

      <!-- 启用状态 -->
      <div class="row">
        <div class="label">启用状态：</div>
        <div class="field">
          <a-radio-group v-model:value="form.enabled" class="control">
            <a-radio :value="true">启用</a-radio>
            <a-radio :value="false">停用</a-radio>
          </a-radio-group>
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="btns">
        <a-button @click="goBack">取 消</a-button>
        <span class="divider" />
        <a-button type="primary" :loading="saving" @click="onSubmit">确 定</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed, onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import { LeftOutlined } from "@ant-design/icons-vue";
import {
  createDefaultKeyword,
  updateDefaultKeyword,
  type DefaultKeywordItem,
  COLLECTION_DEFAULT_SEARCH,
  fetchVerticalCategoryOptions,
} from "@/api/modules/default-search-keyword";
import { getItemById } from "@/api/directus";

/** 路由/编辑态 */
const route = useRoute();
const router = useRouter();
const id = computed(() => route.query.id as string | undefined);
const isEdit = computed(() => Boolean(id.value));
const backToList = computed(() => (route.query.backTo as string) === "list");

/** 表单 */
const saving = ref(false);
const form = reactive({
  name: "",
  channel: "",   
  enabled: true,
});

/** 应用频道：动态选项 */
type ChannelOption = { label: string; value: string | number };
const channelOptions = ref<ChannelOption[]>([]);
const channelLoading = ref(false);
const channelQueriedOnce = ref(false);

async function loadChannelOptions(keyword = "") {
  channelLoading.value = true;
  try {
    const data = await fetchVerticalCategoryOptions({ keyword, page: 1, pageSize: 100 });
    channelOptions.value = (data || []).map((it: any) => ({
      label: it?.query ?? String(it?.value ?? ""),
      value: it?.value,
    }));
  } catch (e: any) {
    message.error(e?.message || "加载频道失败");
  } finally {
    channelLoading.value = false;
  }
}

function onSearchChannel(val: string) {
  loadChannelOptions(val.trim());
}

function onChannelDropdown(open: boolean) {
  if (open && !channelQueriedOnce.value) {
    channelQueriedOnce.value = true;
    loadChannelOptions();
  }
}

/** 返回 */
function goBack() {
  if (backToList.value) {
    router.push({ name: "defaultSearchTerm" });
  } else {
    router.back();
  }
}

/** 加载详情（编辑态） */
async function loadDetail() {
  const d = await getItemById<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, id.value!, {
    fields: ["id", "query", "status", "sence"],
  });
  form.name = d?.query ?? "";
  form.channel = (d?.sence as string) ?? "";
  form.enabled = (d?.status ?? "published") === "published";
}

onMounted(async () => {
  loadChannelOptions();
  if (isEdit.value) {
    try {
      await loadDetail();
    } catch (e: any) {
      message.error(e?.message || "加载详情失败");
    }
  }
});

/** 提交 */
async function onSubmit() {
  if (!form.name.trim()) {
    message.warning("请填写名称");
    return;
  }

  saving.value = true;
  try {
    const ch = (form.channel || "").trim?.() ?? form.channel; 
    if (isEdit.value) {
      const payload: Partial<DefaultKeywordItem> = {
        query: form.name.trim(),
        status: form.enabled ? "published" : "draft",
      };
      if (ch) payload.sence = ch as any; 
      await updateDefaultKeyword(id.value!, payload);
      message.success("保存成功");
    } else {
      const payload: Partial<DefaultKeywordItem> = {
        query: form.name.trim(),
        status: form.enabled ? "published" : "draft",
      };
      if (ch) payload.sence = ch as any;
      await createDefaultKeyword(payload);
      message.success("创建成功");
    }

    if (backToList.value) {
      router.push({ name: "defaultSearchTerm" });
    } else {
      router.back();
    }
  } catch (e: any) {
    message.error(e?.message || "提交失败");
  } finally {
    saving.value = false;
  }
}
</script>

<style scoped>
.wrap {
  min-height: 100vh;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.back {
  padding-left: 0;
  color: #8c8c8c;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #1f1f1f;
}

.form {
  padding: 16px 90px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.row {
  display: grid;
  grid-template-columns: 90px minmax(0, 1fr);
  align-items: center;
  gap: 16px;
}

.label {
  color: #1f1f1f;
}

.required .label::before {
  content: "*";
  color: #ff4d4f;
  margin-right: 4px;
}

.field {
  max-width: 720px;
}

.control {
  width: 100%;
  max-width: 560px;
}

.footer {
  border-top: 1px solid #f0f0f0;
  padding: 16px;
  display: flex;
  justify-content: center;
}

.btns {
  display: flex;
  align-items: center;
}

.divider {
  width: 1px;
  height: 18px;
  background: #f0f0f0;
  margin: 0 12px;
  display: inline-block;
}

@media (max-width:640px) {
  .row {
    grid-template-columns: 1fr;
  }

  .field,
  .control {
    max-width: 100%;
  }

  .label {
    color: #8c8c8c;
  }
}
</style>
